<?php

namespace app\admin\model;

use app\common\enums\StatusEnum;

class TieBaCollect extends \app\common\model\TieBaCollect
{
    /**
     * 我的收藏贴
     * @param $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getList($where)
    {
        $sql = static::field('t.id AS tie_id, t.oauth_id, tt.name, t.praise, t.is_top, t.check_status, t.create_time')
            ->alias('ot')
            ->join('tie_ba t', 'ot.tie_id = t.id')
            ->join('tie_ba_type tt', 't.type_id = tt.id')
            ->where([
                't.is_draft' => TieBa::DRAFT_NO,
                'tt.status' => StatusEnum::ENABLED,
            ]);

        if ($where) {
            $sql->where($where);
        }

        $data = $sql->paginate(null, false, ['query' => request()->param()]);
        $oauthIds = [];
        $tieIds = [];
        foreach ($data->items() as $key => $value) {
            $oauthIds[$value['oauth_id']] = $value['oauth_id'];
            $tieIds[$value['tie_id']] = $value['tie_id'];
        }

        $oauth = [];
        if ($oauthIds) {
            $oauth = Oauth::getColumnValue($oauthIds);
        }

        $comments = [];
        if ($tieIds) {
            // 每条帖子的总评论数
            $comments = TieBaComment::getCount($tieIds);
        }

        $model = $data->each(function ($item, $key) use ($oauth, $comments) {
            $item['comments'] = isset($comments[$item['tie_id']]) ? $comments[$item['tie_id']] : 0;
            $item['oauth_id'] = isset($oauth[$item['oauth_id']]) ? $oauth[$item['oauth_id']]['nickname'] : '未知';
            $item['isTopText'] = TieBa::attributes('is_top', $item['is_top']);
            $item['create_time'] = get_datetime($item['create_time']);
            $item['checkStatusText'] = TieBa::attributes('check_status', $item['check_status']);
            return $item;
        });

        // 获取总记录数
        $count = $model->total();
        return [
            'model' => $model,
            'count' => $count
        ];
    }

}